package com.example.action;

import com.supermap.data.*;
import com.supermap.desktop.controls.ui.controls.DialogResult;
import com.supermap.desktop.controls.ui.controls.SmDialog;
import com.supermap.desktop.core.Application;
import com.supermap.desktop.core.Interface.IFormTabular;
import com.supermap.desktop.core.utilties.CursorUtilities;
import com.supermap.desktop.samplecodetemplates.basicoperation.formtabularuserdefine.dialog.DialogOpenTabular;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class DemoSampleCode extends SmDialog {


    private JTable attributeTable;          // 属性表格
    private JButton openFormTabularButton;  // 打开数据集
    private JButton saveButton;             // 保存按钮
    private JButton startEditButton;      // 启用编辑按钮
    private JButton performOperationButton; // 操作按钮（增删改查、拓扑操作）

    private Recordset recordset;    //当前数据集

    private EditableTableModel tableModel;
    private Set<String> editableColumns = new HashSet<>();

    public DemoSampleCode() {
        initializeUI();
        initListeners();
    }


    private void initializeUI() {
        setTitle("这是一个demo啊");
        setSize(800, 600);
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        // 属性表格展示
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 4;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        attributeTable = new JTable();
        JScrollPane scrollPane = new JScrollPane(attributeTable);
        add(scrollPane, gbc);

        // 按钮区域
        gbc.gridy = 2;
        gbc.gridwidth = 1;
        gbc.weightx = 0.0;
        gbc.weighty = 0.0;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.EAST;

        openFormTabularButton = new JButton("打开数据源");
        gbc.gridx = 0;
        add(openFormTabularButton, gbc);

        startEditButton = new JButton("启用编辑");
        gbc.gridx = 1;
        add(startEditButton, gbc);

        saveButton = new JButton("统一赋值");
        gbc.gridx = 2;
        add(saveButton, gbc);

        performOperationButton = new JButton("执行拓扑操作");
        gbc.gridx = 3;
        add(performOperationButton, gbc);
    }


    private void initListeners() {
        //打开数据源
        openFormTabularButton.addActionListener(e -> {
            CursorUtilities.setWaitCursor();
            try {
                DialogOpenTabular dialog = new DialogOpenTabular();
                dialog.setCheckBoxShowInDialogVisible(false);
                if (dialog.showDialog() == DialogResult.OK) {
                    dialog.dispose();
                    IFormTabular formTabular = dialog.getFormTabular();
                    if (formTabular != null) {
                        recordset = formTabular.getRecordset();
                        // 获取 Recordset 并加载到 JTable
                        loadRecordsetData(formTabular.getRecordset());
                    }

                }
            } catch (Exception ex) {
                Application.getActiveApplication().getOutput().output(ex);
            }
        });


        //启用编辑
        startEditButton.addActionListener(e -> {
            // 设置所有列都可编辑
            FieldInfos fieldInfos = recordset.getFieldInfos();
            int fieldCount = fieldInfos.getCount    ();

            editableColumns.clear();
            for (int i = 0; i < fieldCount; i++) {
                editableColumns.add(fieldInfos.get(i).getName());
            }

            tableModel.setEditableColumns(editableColumns);
            attributeTable.repaint(); // 强制刷新表格显示
        });


        //保存编辑的值
        saveButton.addActionListener(e -> {
            CursorUtilities.setWaitCursor();
            try {

                if (recordset == null || recordset.isClosed()) {
                    JOptionPane.showMessageDialog(this, "数据集未打开或已关闭");
                    return;
                }

                // 进入编辑模式
                recordset.edit();

                TableModel tableModel = attributeTable.getModel();
                int rowCount = tableModel.getRowCount();
                int columnCount = tableModel.getColumnCount();

                // 遍历每一行
                for (int row = 0; row < rowCount; row++) {
                    // 获取表格中的 ID（假设第一列是 ID）
                    Object idObj = tableModel.getValueAt(row, 0);
                    if (!(idObj instanceof Integer)) continue;

                    int id = (Integer) idObj;

                    // 定位到记录
                    if (!recordset.seekID(id)) {
                        continue;
                    }

                    // 更新每个字段
                    for (int col = 0; col < columnCount; col++) {
                        String fieldName = tableModel.getColumnName(col);
                        Object value = tableModel.getValueAt(row, col);
                        //系统字段不可编辑
                        if(fieldName.equals("SmID") || fieldName.equals("SmUserID")){
                            continue;
                        }

                        // 设置字段值
                        recordset.setFieldValue(2, value);
                    }

                    // 提交当前记录更新
                    recordset.update();
                }

                JOptionPane.showMessageDialog(this, "保存成功");
                loadRecordsetData(recordset); // 刷新表格

            } catch (Exception ex) {
                Application.getActiveApplication().getOutput().output(ex);
                JOptionPane.showMessageDialog(this, "保存失败：" + ex.getMessage());
            } finally {
                CursorUtilities.setDefaultCursor();
            }
        });
    }

    private void loadRecordsetData(Recordset recordset) {
        if (recordset == null) return;

        try {
            FieldInfos fieldInfos = recordset.getFieldInfos();
            int fieldCount = fieldInfos.getCount();

            // 初始化表格模型
            tableModel = new EditableTableModel();
            for (int i = 0; i < fieldCount; i++) {
                String fieldName = fieldInfos.get(i).getName();
                tableModel.addColumn(fieldName);
            }

            // 默认只允许编辑部分字段（例如 "name" 和 "age"）
            editableColumns.clear();
            //editableColumns.add("name");
            //editableColumns.add("age");

            tableModel.setEditableColumns(editableColumns);

            // 加载数据
            while (!recordset.isEOF()) {
                Object[] row = new Object[fieldCount];
                for (int i = 0; i < fieldCount; i++) {
                    row[i] = recordset.getValues()[i];
                }
                tableModel.addRow(row);
                recordset.moveNext();
            }

            attributeTable.setModel(tableModel);

        } catch (Exception ex) {
            Application.getActiveApplication().getOutput().output(ex);
        }
    }
}
